package com.jeecms.wicool.action.shops;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.util.DateUtils;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.shops.Coupon;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.user.UserAccount;
import com.jeecms.wicool.entity.user.UserCoupon;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.shops.CouponMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.user.UserAccountMng;
import com.jeecms.wicool.manager.user.UserCouponMng;
import com.jeecms.wicool.manager.user.UserInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

/**
 * 会员卡Action
 */
@Controller
public class CouponAct {
	private static final Logger log = LoggerFactory.getLogger(CouponAct.class);

	@SuppressWarnings("unchecked")
	@RequestMapping("/coupon/v_listCoupon.do")
	public String list(Integer couponType, String couponName, Short status,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(couponType, couponName, status,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		List<Coupon> list = (List<Coupon>) pagination.getList();

		List<Dictionary2> listCouponType = DicMng.getList("coupon_type");
		List<Dictionary2> listCouponStatus = DicMng.getList("coupon_status");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		for (Dictionary2 d : listCouponType) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listCouponStatus) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Coupon p : list) {
			if (map.containsKey(p.getCouponType().toString())) {
				p.setCouponTypeName(map.get(p.getCouponType().toString()));
			}
			if (map2.containsKey(p.getStatus().toString())) {
				p.setStatusName(map2.get(p.getStatus().toString()));
			}
		}
		model.addAttribute("pagination", pagination);
		model.addAttribute("couponType", couponType);
		model.addAttribute("couponName", couponName);
		model.addAttribute("status", status);
		model.addAttribute("listCouponType", listCouponType);
		model.addAttribute("listCouponStatus", listCouponStatus);
		return "shops/list_Coupon";
	}

	@RequestMapping("/coupon/v_addCoupon.do")
	public String add(ModelMap model, HttpServletRequest request) {
		Coupon coupon = new Coupon();
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> listCouponType = DicMng.getList("coupon_type");
		model.addAttribute("coupon", coupon);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listCouponType", listCouponType);
		return "shops/add_Coupon";
	}

	@RequestMapping("/coupon/v_editCoupon.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Coupon coupon = manager.findById(id);
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> listCouponType = DicMng.getList("coupon_type");
		model.addAttribute("coupon", coupon);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listCouponType", listCouponType);
		return "shops/edit_Coupon";
	}

	@RequestMapping("/coupon/v_viewCoupon.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Coupon coupon = manager.findById(id);
		coupon.setCouponTypeName(DicMng.findByDicCode("coupon_type",
				Short.parseShort(String.valueOf(coupon.getCouponType())))
				.getDicName());
		coupon.setStatusName(DicMng.findByDicCode("coupon_status",
				Short.parseShort(String.valueOf(coupon.getStatus())))
				.getDicName());
		model.addAttribute("coupon", coupon);
		return "shops/view_Coupon";
	}

	@RequestMapping("/coupon/o_saveCoupon.do")
	public String save(Coupon bean, Integer shopId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean.setStatus(Short.parseShort("1"));
		bean.setPublisher(CmsUtils.getUser(request));
		bean = manager.save(bean, shopId);
		log.info("save Coupon id={}", bean.getId());
		cmsLogMng.operating(request, "Coupon.log.save", "id=" + bean.getId());
		return "redirect:v_listCoupon.do";
	}

	@RequestMapping("/coupon/o_updateCoupon.do")
	public String update(Coupon bean, Integer couponType, String couponName,
			Short status, Integer shopId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.update(bean, shopId);
		model.addAttribute("message", "global.success");
		log.info("update Coupon success. id={}", bean.getId());
		cmsLogMng.operating(request, "Coupon.log.update", "id=" + bean.getId());
		return list(couponType, couponName, status, pageNo, request, model);
	}

	@RequestMapping("/coupon/o_deleteCoupon.do")
	public String delete(Integer[] ids, Integer couponType, String couponName,
			Short status, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Coupon[] beans = manager.deleteByIds(ids);
		for (Coupon bean : beans) {
			log.info("delete Coupon id={}", bean.getId());
			cmsLogMng.operating(request, "Coupon.log.delete",
					"id=" + bean.getId() + ";name=" + bean.getCouponName());
		}
		return list(couponType, couponName, status, pageNo, request, model);
	}

	@RequestMapping("/coupon/v_toXfCoupon.do")
	public String toXfCoupon(Integer id, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("id", id);
		return "shops/to_xf_coupon";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/coupon/v_xf_user.do")
	public String toXfCouponForUser(Integer couponId,Integer shopId,String userName,String mobile,Integer pageNo, HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateEdit(couponId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Coupon coupon = manager.findById(couponId);
		model.addAttribute("coupon", coupon);
		// 会员信息
		Pagination pagination = userAccountMng.getPage(shopId,userName,mobile,cpn(pageNo),CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		List<UserAccount> list = (List<UserAccount>) pagination.getList();
		List<Dictionary2> listVipLevel=DicMng.getList("vip_level");
		for (UserAccount userAccount : list) {
			if(userAccount.getVipLevel() != null){
				for (Dictionary2 vipLevel : listVipLevel) {
					if(vipLevel.getDicCode().intValue() == userAccount.getVipLevel().intValue()){
						userAccount.setVipLevelName(vipLevel.getDicName());
						break;
					}
				}
			}
		}
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("shopList",shopList);
		model.addAttribute("shopId",shopId);
		model.addAttribute("userName",userName);
		model.addAttribute("mobile",mobile);
		return "shops/xf_coupon_user";
	}

	@RequestMapping("/coupon/v_xf_vipLevel.do")
	public String toXfCouponForVipLevel(Integer id, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Coupon coupon = manager.findById(id);
		model.addAttribute("coupon", coupon);

		List<Dictionary2> vipLevels = DicMng.getList("vip_level");
		model.addAttribute("vipLevels", vipLevels);

		return "shops/xf_coupon_viplevel";
	}

	@RequestMapping("/coupon/o_xf_coupon_viplevel.do")
	public String xfCouponForVipLevel(Integer id, Integer vipLevel, Integer pageNo,
			HttpServletRequest request, ModelMap model) throws ParseException {
		WebErrors errors = validateUpdate(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		Coupon coupon = manager.findById(id);
		
		SimpleDateFormat simpleTime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);
		
		/** 处理优惠劵失效时间 **/
		Calendar c = Calendar.getInstance();
		c.setTime(simpleTime.parse(dateTime));
		c.add(Calendar.DATE, coupon.getValidityDays());
		String dateEnd = simpleTime.format(c.getTime());
		Timestamp endTime = Timestamp.valueOf(dateEnd);
		/** 处理失效时间结束 **/
		
		List<UserCoupon> userCouponList = manager.findByCouponId(id);
		
		List<UserAccount> userList = userAccountMng.getListUserAccountByVipLevel(vipLevel);
		
		if(userList == null || userList.isEmpty()){
			model.addAttribute("message", "没有找到符合条件的会员信息");
			return toXfCouponForVipLevel(id, request, model);
		}
		
		for (UserAccount userAccount : userList) {
			// 判断此优惠券是否已下发该用户手里
			Boolean isHaveData = false;
			if(userCouponList != null && !userCouponList.isEmpty()){
				for (UserCoupon userCoupon : userCouponList) {
					if(userAccount.getUser().getId().equals(userCoupon.getUser().getId())){
						isHaveData = true;
						break;
					}
				}
			}
			if(!isHaveData){
				UserCoupon uc = new UserCoupon();
				uc.setCouponType(coupon.getCouponType());
				uc.setCouponSource(2);
				uc.setStatus(Short.parseShort("1"));
				uc.setCreateTime(t);
				uc.setEndTime(endTime);
				userCouponMng.save(uc, userAccount.getUser().getId(), coupon.getId());
			}
		}
		coupon.setStatus(Short.parseShort("2"));
		coupon = manager.update(coupon, coupon.getShop().getId());
		model.addAttribute("message", "global.success");
		log.info("update Coupon success. id={}", coupon.getId());
		cmsLogMng.operating(request, "Coupon.log.update","id=" + coupon.getId());
		return toXfCouponForVipLevel(id, request, model);
	}
	
	@RequestMapping("/coupon/o_xf_coupon_user.do")
	public String xfCouponForUsers(Integer id, Integer[] userIds, Integer pageNo,
			HttpServletRequest request, ModelMap model) throws ParseException {
		WebErrors errors = validateUpdate(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		Coupon coupon = manager.findById(id);
		
		SimpleDateFormat simpleTime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);
		
		/** 处理优惠劵失效时间 **/
		Calendar c = Calendar.getInstance();
		c.setTime(simpleTime.parse(dateTime));
		c.add(Calendar.DATE, coupon.getValidityDays());
		String dateEnd = simpleTime.format(c.getTime());
		Timestamp endTime = Timestamp.valueOf(dateEnd);
		/** 处理失效时间结束 **/

		List<UserCoupon> userCouponList = manager.findByCouponId(id);
		int savecount = 0;
		for (Integer userId : userIds) {
			// 判断此优惠券是否已下发该用户手里
			Boolean isHaveData = false;
			if(userCouponList != null && !userCouponList.isEmpty()){
				for (UserCoupon userCoupon : userCouponList) {
					if(userId.equals(userCoupon.getUser().getId())){
						isHaveData = true;
						break;
					}
				}
			}
			if(!isHaveData){
				UserCoupon uc = new UserCoupon();
				uc.setCouponType(coupon.getCouponType());
				uc.setCouponSource(2);
				uc.setStatus(Short.parseShort("1"));
				uc.setCreateTime(t);
				uc.setEndTime(endTime);
				userCouponMng.save(uc, userId, coupon.getId());
				savecount++;
			}
		}
		if(savecount > 0){
			coupon.setStatus(Short.parseShort("2"));
			coupon = manager.update(coupon, coupon.getShop().getId());
			model.addAttribute("message", "global.success");
			log.info("update Coupon success. id={}", coupon.getId());
			cmsLogMng.operating(request, "Coupon.log.update","id=" + coupon.getId());
		}else{
			model.addAttribute("message", "所选用户已下发了此优惠卷，无法操作！！！");
		}
		return toXfCouponForUser(id, null, null, null, pageNo, request, model);
	}

	//财务优惠券下发审核
	@SuppressWarnings("unchecked")
	@RequestMapping("/coupon/v_adultlistCoupon.do")
	public String adultlistCoupon(Integer couponType, String couponName,String mobile, Short status,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		
		Pagination pagination = userCouponMng.getPage(null, couponType,mobile, couponName, null, status, cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		
		List<UserCoupon> list = (List<UserCoupon>) pagination.getList();

		List<Dictionary2> listCouponType = DicMng.getList("coupon_type");
		List<Dictionary2> listCouponStatus = DicMng.getList("coupon_adult_status");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		for (Dictionary2 d : listCouponType) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listCouponStatus) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (UserCoupon p : list) {
			if (map.containsKey(p.getCouponType().toString())) {
				p.setCouponTypeName(map.get(p.getCouponType().toString()));
			}
			if (map2.containsKey(p.getStatus().toString())) {
				p.setStatusName(map2.get(p.getStatus().toString()));
			}
			
			if(p.getUsedTime() != null){
				p.setUsedTimeStr(DateUtils.format3.format(new Date(p.getUsedTime().getTime())));
			}
			
			if(p.getCreateTime() != null){
				p.setCreateTImeStr(DateUtils.format3.format(new Date(p.getCreateTime().getTime())));
			}
			
			if(p.getEndTime() != null){
				p.setEndTimeStr(DateUtils.format3.format(new Date(p.getEndTime().getTime())));
			}
		}
		model.addAttribute("pagination", pagination);
		model.addAttribute("couponType", couponType);
		model.addAttribute("couponName", couponName);
		model.addAttribute("status", status);
		model.addAttribute("listCouponType", listCouponType);
		model.addAttribute("listCouponStatus", listCouponStatus);
		return "finance/list_adultcoupon";
	}
	
	@RequestMapping("/coupon/o_adult.do")
	public String adult(Integer[] ids, HttpServletRequest request, ModelMap model) {
		
		for (Integer id : ids) {
			UserCoupon o =	userCouponMng.findById(id);
			o.setStatus(Short.valueOf("2"));//已审核
			userCouponMng.update(o, o.getUser().getId(), o.getCoupon().getId());
		}
		model.addAttribute("message", "global.success");
		return adultlistCoupon(null, null,null, null, null, request, model);
	}
	
	private WebErrors validateSave(Coupon bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Coupon entity = manager.findById(id);
		if (errors.ifNotExist(entity, Coupon.class, id)) {
			return true;
		}
		return false;
	}

	@Autowired
	private CouponMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private UserInfoMng userMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private UserCouponMng userCouponMng;
	@Autowired
	private UserAccountMng userAccountMng;
}
